package ks.server.controllers.commands.general.user;

import java.util.Collection;
import java.util.Vector;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.server.persist.PersistentUserManager;
import ks.server.ServerContext;

import org.w3c.dom.Document;

/**
 * Process request to send status of player accounts on system.
 * 
 * @author Christopher Page
 */
public class UserConnectedController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public UserConnectedController (Communicator com) {
		this.com = com;
	}
	
	/**
	 * Process the message
	 * 
	 * @param m The message to process.
	 * @return A boolean value.
	 */
	public boolean process(Message m) {
		PersistentUserManager um = ServerContext.getUserManager();
		
		// get usernames of online users
		Collection<String> onlineUsernames = com.getOnlineUsers();
		
		// get User instances of online users
		Vector<User> onlineUsers = new Vector<User>(0);
		User u;
		for (String username : onlineUsernames) {
			u = um.getUser(username);
			if (u != null)
				onlineUsers.add(u);
		}
		
		// build request
		StringBuilder sb = new StringBuilder("<request version='1.0' id='589a39591271844e3fbe32bbb9281ad9'>");
		sb.append("<users>");
		for (User u2 : onlineUsers) {
			sb.append("<allplayer name=\"" + u2.getName() + "\" rating=\"" + u2.getRating() + "\" icon=\"" + u2.getIconName() + "\" online=\"true\" />");
		}
		sb.append("</users>");
		sb.append("</request>");
		
		// send request to command originator
		Document d = Message.construct(sb.toString());
		Message r = new Message(d);
		r.setRecipient(m.getOriginator());
		return com.distribute(r);
	}
}
